package ewan.android.droidjockey;

import java.util.List;

import ewan.android.droidjockey.R;

import ewan.android.droidjockey.MusicRetriever.Item;

import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

public class PlayListFragment extends ListFragment {

	private int currentPosition = 0;
	Button nowPlaying;
	Button backButton;
	ProgressBar progress;
	boolean threadWait = false;
	boolean created = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		View songList = inflater.inflate(R.layout.songlist, container, false);
		Context ctx = (Context) PlayListFragment.this.getActivity();
		// Inflate the layout for this fragment
		
		setListAdapter(new ArrayAdapter<String>(ctx, R.layout.song_item,
				MusicRetriever.getCurrentPlaylist()));
		backButton = (Button) songList.findViewById(R.id.goback);
		backButton.setText("Current Playlist");
		nowPlaying = (Button) songList.findViewById(R.id.playing);
		nowPlaying.setSelected(true);
		nowPlaying.setEllipsize(TruncateAt.MARQUEE);
		nowPlaying.setSingleLine(true);
		progress = (ProgressBar) songList.findViewById(R.id.progress);

		try {
			nowPlaying.setText(MusicRetriever.getCurrentSong().getTitle()
					.toString());
			progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
		} catch (Exception e) {
		}
		// }
		nowPlaying.setOnClickListener(new OnClickListener() {

			public void onClick(View target) {

				if (target == nowPlaying) {
					Intent intent = new Intent();
					PlayListFragment.this.getActivity().setResult(1, intent);
					PlayListFragment.this.getActivity().finish();
				}

			}
		});
		if (!thread.isAlive()){
		thread.start();
		}
		return songList;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		Context ctx = (Context) PlayListFragment.this.getActivity();
		currentPosition = position;
		System.out.println(MusicRetriever.mainSongList);
		System.out.println(MusicRetriever.usingGenPlaylist);
		System.out.println(MusicRetriever.usingPlaylist);
		List<Item> s = MusicRetriever.getOrderedSongs();
		Item toPlay = s.get(currentPosition);
		Intent i = new Intent(MusicService.ACTION_URI);
		i.putExtra("Position", currentPosition);
		System.out.println(toPlay.getURI().toString());
		// startActivity(i);
		ctx.startService(i);
		Intent intent = new Intent();
		PlayListFragment.this.getActivity().setResult(1, intent);
		if (MusicRetriever.shuffle){
			MusicRetriever.shuffle = false;
			ctx.startService(new Intent(MusicService.ACTION_SHUFFLE));
		}
		PlayListFragment.this.getActivity().finish();
	}

	public void onDestroyView(){
		super.onDestroyView();
	}
	
	Thread thread = new Thread() {
		public synchronized void run() {

			while (true) {
				try {

						while (MusicService.State.Playing != null) {

							try {
								Message position = new Message();
								position.what = MusicService.mPlayer
										.getCurrentPosition();
								threadHandler.sendMessage(position);
								if (MusicService.State.Playing != null) {
									if (!nowPlaying.getText().equals(
											MusicRetriever.getCurrentSong()
													.getTitle().toString())) {

										Message update = new Message();
										update.what = 0;
										UIHandler.sendMessage(update);

									}
								}
							} catch (NullPointerException e) {
							} catch (Exception e) {
								e.printStackTrace();
							}
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								Thread.currentThread().interrupt();
						        break;
							}
						}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
				        break;
					}
				} catch (IndexOutOfBoundsException e) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						Thread.currentThread().interrupt();
				        break;
					}
				}
			}
		}

	};
		
		public synchronized void onPause() {
			super.onPause();
		}
		
		public synchronized void onDestroy() {
			super.onDestroy();
			thread.interrupt();
		}
		
		public synchronized void onResume() {
			super.onResume();
			try {
				progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
				Message position = new Message();
				position.what = MusicService.mPlayer.getCurrentPosition();
				threadHandler.sendMessage(position);
			} catch (Exception e) {
			}
		}

	public Handler UIHandler = new Handler() {

		public synchronized void handleMessage(Message msg) {
			if (msg.what == 0) {
				try {
					nowPlaying.setText(MusicRetriever.getCurrentSong()
							.getTitle().toString());
					progress.setMax((int) MusicRetriever.getCurrentSong()
							.getDuration());
				} catch (Exception e) {
				}
			}
		}
	};

	private Handler threadHandler = new Handler() {

		public synchronized void handleMessage(Message msg) {
			try {
				progress.setProgress(msg.what);
			} catch (NullPointerException e) {
			}
		}
	};

}